﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using FeishuWorkflowService.Services;

namespace FeishuWorkflowService.Filters
{
    public class OomExceptionFilter : IExceptionFilter
    {
        private readonly ILogger<OomExceptionFilter> _logger;
        private readonly MemoryMonitorService _memoryMonitor;

        public OomExceptionFilter(ILogger<OomExceptionFilter> logger, MemoryMonitorService memoryMonitor)
        {
            _logger = logger;
            _memoryMonitor = memoryMonitor;
        }

        public void OnException(ExceptionContext context)
        {
            if (context.Exception is OutOfMemoryException oomEx)
            {
                // 记录内存溢出堆栈
                _logger.LogCritical(oomEx, "发生内存溢出异常");

                // 生成内存溢出时的dump
                _memoryMonitor.GenerateDumpByTool("OOM");

                // 返回友好响应
                context.Result = new ObjectResult(new
                {
                    message = "服务器内存溢出，请稍后重试",
                    timestamp = DateTime.Now
                })
                {
                    StatusCode = 500
                };
                context.ExceptionHandled = true;
            }
        }
    }
}
